<?php

namespace App\Services\Store\Sponsor;

use App\Exceptions\SponsorException;
use App\Models\Applet\User\UserIntegralRecordsModel;
use App\Models\Applet\User\UserSponsorModel;
use Exception;
use Illuminate\Support\Facades\DB;

class SponsorService extends BaseSponsorService
{
    /**
     * 认养列表
     * @param array $params
     * @return array
     * @throws Exception
     */
    public function list(array $params): array
    {
        // 查询认养列表
        $userSponsorList = $this->getUserSponsorModel()->storeList($params, [
            'id', 'name', 'cover_img', 'cycle', 'start_time', 'quantity', 'status'
        ]);

        $userSponsorIds = array_column($userSponsorList, 'id');


        // 查询宰杀申请记录
        $userSlaughterRecordsList = $this->getUserSlaughterRecordsModel()->getItemsByIds($userSponsorIds, [
            'id', 'user_sponsor_id', 'created_at'
        ]);
        $userSlaughterRecordsListMap = array_column($userSlaughterRecordsList, null, 'user_sponsor_id');

        $list = [];
        foreach ($userSponsorList as $item) {

            $coverTime = '';
            if ($item['status'] == UserSponsorModel::STATUS_DEFAULT) {
                $coverTime = date('Y-m-d H:i:s', strtotime($item['start_time']) + $item['cycle'] * 24 * 60 * 60);
            }
            if (isset($userSlaughterRecordsListMap[$item['id']])) {
                $coverTime = $userSlaughterRecordsListMap[$item['id']]['created_at'];
            }

            $list[] = [
                'id' => $item['id'],
                'name' => $item['name'],
                'coverImg' => $item['cover_img'],
                'coverTime' => $coverTime,
                'quantity' => $item['quantity'],
            ];
        }

        return [
            'list' => $list,
        ];
    }

    /**
     * 认养详情
     * @param array $params
     * @return array[]
     * @throws SponsorException
     * @throws Exception
     */
    public function detail(array $params): array
    {
        // 查询认养详情
        $detail = $this->getUserSponsorModel()->getItemById($params['id'], [
            'id', 'name', 'start_time', 'cycle', 'quantity'
        ]);
        if (empty($detail)) {
            throw new SponsorException('用户认养记录不存在', SponsorException::CODE_4001);
        }

        // 查询认养详情图片列表
        $sponsorImgList = $this->getUserSponsorImgModel()->getItemByUserSponsorId($params['id'], [
            'id', 'user_sponsor_id', 'img_url', 'created_at'
        ]);

        $coverTime = date('Y-m-d H:i:s', strtotime($detail['start_time']) + $detail['cycle'] * 24 * 60 * 60);

        $list = [];
        foreach ($sponsorImgList as $item) {
            $list[] = [
                'id' => $item['id'],
                'imgUrl' => $item['img_url'],
                'createdAt' => $item['created_at'],
            ];
        }

        return [
            'id' => $detail['id'],
            'name' => $detail['name'],
            'coverTime' => $coverTime,
            'quantity' => $detail['quantity'],
            'list' => $list
        ];
    }

    /**
     * 快递公司列表
     * @return array
     * @throws Exception
     */
    public function expressCompanyList(): array
    {
        // 快递公司列表
        $list = $this->getExpressCompanyModel()->list([
            'id', 'name', 'code'
        ]);

        return [
            'list' => $list
        ];
    }

    /**
     * 上传图片
     * @param array $params
     * @return void
     * @throws Exception
     */
    public function update(array $params)
    {
        // 查询用户认养记录
        $detail = $this->getUserSponsorModel()->getItemById($params['id']);
        if (empty($detail)) {
            throw new SponsorException('用户认养记录不存在', SponsorException::CODE_4001);
        }

        $createUserSponsorImg = [
            'user_sponsor_id' => $params['id'],
            'img_url' => $params['imgUrl'],
        ];

        $this->getUserSponsorImgModel()->addItem($createUserSponsorImg);
    }

    /**
     * 发放积分
     * @return void
     * @throws Exception
     */
    public function grantIntegral(array $params)
    {
        // 查询认养详情
        $detail = $this->getUserSponsorModel()->getItemById($params['id'], [
            'id', 'user_id'
        ]);
        if (empty($detail)) {
            throw new SponsorException('用户认养记录不存在', SponsorException::CODE_4001);
        }

        $createUserIntegralRecords = [
            'user_id' => $detail['user_id'],
            'type' => UserIntegralRecordsModel::TYPE_INCREMENT,
            'quantity' => $params['integral'],
        ];

        // 发放积分
        DB::transaction(function () use ($detail, $params, $createUserIntegralRecords) {
            // 更新用户积分
            $this->getUserModel()->incrementIntegral($detail['user_id'], $params['integral']);
            // 添加发放用户积分记录
            $this->getUserIntegralRecordsModel()->addItem($createUserIntegralRecords);
        });
    }

    /**
     * 发放快递
     * @return void
     * @throws Exception
     */
    public function createExpress(array $params)
    {
        // 查询用户认养记录
        $detail = $this->getUserSponsorModel()->getItemById($params['id']);
        if (empty($detail)) {
            throw new SponsorException('用户认养记录不存在', SponsorException::CODE_4001);
        }

        $createSlaughterExpress = [
            'express_company_code' => $params['expressCompanyCode'],
            'express_no' => $params['expressNo'],
        ];

        $this->getSlaughterExpressModel()->addItem($createSlaughterExpress);
    }
}
